<%@page import="java.io.*"%>
<%@page import="org.coody.framework.util.StringUtil"%>
<%@page import="com.ezone.web.util.ImageTagExportUtil"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String action = request.getParameter("action");
	if ("parse".equals(action)) {
		try {
			MultipartFile file = Uploader.getFile(request, "file");
			Map<String, String> map = ImageTagExportUtil.exportImageTags(file.getFileContext());
			StringBuilder sb = new StringBuilder();
			for (String key : map.keySet()) {
				sb.append(key).append(":").append(map.get(key)).append("\r\n");
			}
			out.print(sb.toString());
		} catch (Exception e) {
			out.print(e.toString());
		}
		return;
	}
%>


<%!public static class Uploader {
		public static byte[] toByteArray(InputStream input) {
			try {
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				byte[] buffer = new byte[4096];
				int n = 0;
				while (-1 != (n = input.read(buffer))) {
					output.write(buffer, 0, n);
				}
				return output.toByteArray();
			} catch (Exception e) {
				return null;
			}

		}
		/**
		 * Http协议是世界上最邋遢的协议，没有之一。
		 * 
		 * @param data
		 * @param boundary
		 * @return
		 * @throws IOException
		 */
		public static MultipartFile getFile(HttpServletRequest request, String fieldName) throws Exception {

			byte[] data = toByteArray(request.getInputStream());
			String boundary = getBoundary(request);
			if (StringUtil.isNullOrEmpty(data)) {
				return null;
			}
			Map<String, List<Object>> resultMap = new HashMap<String, List<Object>>();
			try {
				String context = new String(data, "ISO-8859-1");
				String boundaryTag = "--" + boundary;
				String[] paramContexts = context.split(boundaryTag);
				for (String paramContext : paramContexts) {
					MultipartFile multipartFile = buildMultipartFile(paramContext);
					if (StringUtil.isNullOrEmpty(multipartFile)) {
						continue;
					}
					if (!resultMap.containsKey(multipartFile.getParamName())) {
						List<Object> files = new ArrayList<Object>();
						resultMap.put(multipartFile.getParamName(), files);
					}
					resultMap.get(multipartFile.getParamName()).add(multipartFile);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return (MultipartFile) resultMap.get(fieldName).get(0);
		}

		private static String getBoundary(HttpServletRequest request) {
			String line = request.getHeader("Content-Type");
			String[] dabbles = line.split(";");
			String boundary = "";
			for (String dabble : dabbles) {
				int index = dabble.indexOf("=");
				if (index < 1 || index > dabble.length()) {
					continue;
				}
				String name = dabble.substring(0, dabble.indexOf("=")).trim();
				String value = dabble.substring(dabble.indexOf("=") + 1);
				if (name.equals("boundary")) {
					boundary = value;
				}
			}
			return boundary;
		}

		private static MultipartFile buildMultipartFile(String paramContext) {
			if (StringUtil.isNullOrEmpty(paramContext)) {
				return null;
			}
			ByteArrayInputStream inputStream = null;
			try {
				inputStream = new ByteArrayInputStream(paramContext.trim().getBytes("ISO-8859-1"));
				String line = readLineString(inputStream).trim();
				String contextType = "text/plain";
				Map<String, String> buildMap = buildParaMap(line);
				if (StringUtil.isNullOrEmpty(buildMap)) {
					return null;
				}
				String paramName = buildMap.get("name");
				if (StringUtil.isNullOrEmpty(paramName)) {
					return null;
				}
				line = readLineString(inputStream).trim();
				if (line.contains("Content-Type")) {
					contextType = line.substring(line.indexOf(":") + 1).trim();
				}
				while (!StringUtil.isNullOrEmpty(line)) {
					line = readLineString(inputStream).trim();
				}
				byte[] value = getBytes(inputStream);
				MultipartFile multipartFile = new MultipartFile();
				multipartFile.setContextType(contextType);
				multipartFile.setFileContext(value);
				multipartFile.setParamName(buildMap.get("name"));
				multipartFile.setFileName(buildMap.get("filename"));
				return multipartFile;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		public static byte[] getBytes(InputStream ins) {
			ByteArrayOutputStream swapStream = null;
			try {
				swapStream = new ByteArrayOutputStream();
				byte[] buff = new byte[1024];
				int rc = 0;
				while ((rc = ins.read(buff, 0, 1024)) > 0) {
					swapStream.write(buff, 0, rc);
				}
				return swapStream.toByteArray();
			} catch (Exception e) {

				return null;
			} finally {
				try {
					swapStream.close();
				} catch (IOException e) {

				}
			}
		}
		private static Map<String, String> buildParaMap(String context) {
			if (context.contains(":")) {
				context = context.substring(context.indexOf(":") + 1);
			}
			String[] lines = context.split("; ");
			Map<String, String> paraMap = new HashMap<String, String>();
			for (String line : lines) {
				if (!line.contains("=")) {
					continue;
				}
				String name = line.substring(0, line.indexOf("=")).trim();
				String value = line.substring(line.indexOf("=") + 1).replace("\"", "").trim();
				if (StringUtil.hasNull(name, value)) {
					continue;
				}
				paraMap.put(name, value);
			}
			if (StringUtil.isNullOrEmpty(paraMap)) {
				return null;
			}
			return paraMap;
		}
		public static byte[] readLine(InputStream inputStream) throws IOException {
			ByteArrayOutputStream swapStream = null;
			try {
				swapStream = new ByteArrayOutputStream();
				int chr = -1;
				while ((chr = inputStream.read()) != -1) {
					swapStream.write(chr);
					if (chr == 10) {
						break;
					}
				}
				return swapStream.toByteArray();
			} catch (Exception e) {
				return null;
			} finally {
				swapStream.close();
			}
		}
		public static String readLineString(InputStream inputStream) {
			try {
				byte[] data = readLine(inputStream);
				if (StringUtil.isNullOrEmpty(data)) {
					return null;
				}
				return new String(data, "UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}

	public static class MultipartFile {

		private String paramName;

		private String fileName;

		private byte[] fileContext;

		private String suffix;

		private String contextType;

		public String getContextType() {
			return contextType;
		}

		public void setContextType(String contextType) {
			this.contextType = contextType;
		}

		public String getParamName() {
			return paramName;
		}

		public void setParamName(String paramName) {
			this.paramName = paramName;
		}

		public String getFileName() {
			return fileName;
		}

		public void setFileName(String fileName) {
			this.fileName = fileName;
			this.suffix = getSuffix(fileName);
		}

		public byte[] getFileContext() {
			return fileContext;
		}

		public void setFileContext(byte[] fileContext) {
			this.fileContext = fileContext;
		}

		public String getSuffix() {
			return suffix;
		}

		public void setSuffix(String suffix) {
			this.suffix = suffix;
		}

		private String getSuffix(String fileName) {
			if (StringUtil.isNullOrEmpty(fileName)) {
				return null;
			}
			String[] strs = fileName.split("\\.");
			return strs[strs.length - 1].toLowerCase();
		}

		@Override
		public String toString() {
			return "MultipartFile [paramName=" + paramName + ", fileName=" + fileName + ", fileContext="
					+ Arrays.toString(fileContext) + ", suffix=" + suffix + ", contextType=" + contextType + "]";
		}
	}%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<jsp:include page="header.jsp" />
</head>
<body>
	<jsp:include page="js.jsp" />
	<div class="am-g">
		<div class="am-u-md-12">
			<div class="am-panel am-panel-default">
				<div class="am-panel-hd">${utils.title }</div>
				<div class="am-panel-bd">
					<div class="am-form">
						<fieldset>
							<div class="am-form-group am-form-success">
								<div class="am-form-group am-form-file">
									<button type="button" class="am-btn am-btn-danger am-btn-sm">
										<i class="am-icon-cloud-upload"></i> 选择要上传的文件
									</button>
									<input id="doc-form-file" type="file" multiple>
								</div>


							</div>
							<div class="am-form-group">
								<textarea id="targeId" style="height: 40rem"></textarea>
							</div>
						</fieldset>
					</div>
				</div>
			</div>
			<jsp:include page="foot.jsp" />
		</div>
	</div>
</body>
<script>
	$('#doc-form-file').on('change', function() {
		var file = this.files[0];
		var fileName = file.name;
		var fileType = fileName.substr(fileName.length - 4, fileName.length);
		var formData = new FormData()
		formData.append("file", file);
		$.ajax({
			url : '?action=parse',
			type : 'POST',
			cache : false,
			data : formData,
			dataType : "text",
			processData : false,
			contentType : false,
			success : function(text) {
				$("#targeId").html(text.trim());
			}
		});
	});
</script>
<script type='text/javascript'>
	function doFormat() {
		var json = format($("#currId").val());
		$('#targeId').val(json);
	}
</script>
</html>
